package easycmd

import (
	"fmt"
	"os"
)

// cmdContext 命令容器
type cmdContext struct {
	cmdMap map[string]*Command // 命令名称和命令对象map
}

// 全局命令容器对象
var ctx = &cmdContext{
	cmdMap: make(map[string]*Command, 16),
}

// 命令注册到容器中
func (ctx *cmdContext) add(cmd *Command) {
	if cmd == nil {
		panic("command must be not nil")
	}
	if _, ok := ctx.cmdMap[cmd.name]; !ok {
		ctx.cmdMap[cmd.name] = cmd
	}
}

// 容器启动
func (ctx *cmdContext) run() {
	if len(os.Args) < 1 {
		fmt.Println("please enter commands")
		os.Exit(1)
	}

	cmdName := os.Args[1]
	cmd, existCmd := ctx.cmdMap[cmdName]
	if !existCmd {
		switch parseArg(cmdName) {
		case "help", "h": // 列出所有命令及其参数详情
			for name, cmdItem := range ctx.cmdMap {
				f := cmdItem.f
				desc := cmdItem.desc
				fmt.Fprintf(f.Output(), "Usage of %s(%s):\n", name, desc)
				f.PrintDefaults()
				fmt.Fprintf(f.Output(), "\n")
			}
			os.Exit(0)
		case "l": // 列出所有命令及其描述
			fmt.Println("Cmd list:")
			for name, cmdItem := range ctx.cmdMap {
				f := cmdItem.f
				desc := cmdItem.desc
				fmt.Fprintf(f.Output(), "  %s - %s\n", name, desc)
			}
			os.Exit(0)
		default:
			fmt.Println("commands not exist: " + cmdName)
			os.Exit(1)
		}
	}

	cmd.execute()
}

func parseArg(arg string) string {
	if len(arg) < 2 || arg[0] != '-' {
		return ""
	}
	numMinuses := 1
	if arg[1] == '-' {
		numMinuses++
		if len(arg) == 2 { // "--" terminates the flags
			return ""
		}
	}
	name := arg[numMinuses:]
	if len(name) == 0 || name[0] == '-' || name[0] == '=' {
		return ""
	}
	return name
}
